package nl.project.registration;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.project.data.Employee;
import nl.project.data.Parent;
import nl.project.data.controller.MembersDAO;

public class Forwarder extends HttpServlet {
	/**
	 * If the user gets here, then they must have got here manually (without redirect from
	 * login page). So first check if the user has logged in. 
	 */
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws IOException {
		try {
			if (req.getSession().getAttribute("user") != null) {
				doPost(req, resp);
				
			} else {
				//user needs to login
				resp.sendRedirect("");
			}
		} catch (ServletException e) {
			//return something like: "Something went wrong! If problem stays, contact admin!"
			e.printStackTrace();
			resp.sendRedirect("");
		}
	}

	/**
	 * If user gets here, then the parent is succesfully logged in, so now we
	 * need extra info for the registration form.
	 */
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try{
			Parent p = (Parent) req.getSession().getAttribute("user");
			if (p.getStudents() != null) {
				ArrayList<Object> students = p.getStudents();
				
				if (students.size() > 1) {
					getServletContext().getRequestDispatcher("/student_select.jsp").forward(req, resp);
				} else {
					getServletContext().getRequestDispatcher("/registration").forward(req, resp);
				}
			}
		} catch(Exception e){
			getServletContext().getRequestDispatcher("/student_select.jsp").forward(req, resp);
		}
	}
}